# -*- coding: utf-8 -*- #
"""
Time                2022/11/14 14:32
Author:             mingfeng (SunnyQjm)
Email               mfeng@linux.alibaba.com
File                ssh.py
Description:
"""
from clogger import logger
from fastapi import FastAPI
from app.routers import health
from conf.settings import YAML_CONFIG
from sysom_utils import CmgPlugin, SysomFramework
import time
import sys,os,json
sys.path.append("%s/lib"%(os.path.dirname(os.path.abspath(__file__))))
#import datetime
import traceback
from datetime import date, datetime, timedelta
from app.crud import create_knowledge,create_knowledge_record
from app.crud import get_knowledge_by_calltrace,get_knowledge_by_logs,get_knowledge_by_funcs
from app.schemas import Knowledge,KnowledgeRecord
from app.database import SessionLocal
from extract_calltrace import extract_calltrace

app = FastAPI()

app.include_router(health.router, prefix="/api/v1/knowledge/health")

db = SessionLocal()

#############################################################################
# Write your API interface here, or add to app/routes
#############################################################################

@app.post("/api/v1/knowledge/input")
async def knowledge_input(request: dict):
    retdict = {"success":False,"errmsg":""}
    param_list = ["logs","funcs","calltrace","issuedesc","issuelink","diagret","field"]

    try:
        errmsg = ""
        for param in param_list:
            if param not in request:
                errmsg += "Missing parametre: %s\n"%param
                retdict["errmsg"] = errmsg
        if len(errmsg) > 0:
            return retdict
        if len(request["logs"]) == 0 and len(request["calltrace"]) == 0 and len(request["funcs"]) == 0:
            errmsg += "logs, funcs and calltrace could not be all empty!\n"
        if len(request["issuedesc"]) == 0 and len(request["issuelink"]) == 0 and len(request["diagret"]) == 0:
            errmsg += "issuedesc, issuelink and diagret could not be all empty!\n"
        if len(request["field"]) == 0:
            errmsg += "field could not be empty!\n"
        if len(errmsg) > 0:
            retdict["errmsg"] = errmsg
            return retdict

        calltrace_extrack = request["calltrace"]
        if len(request["calltrace"]) > 0:
            column = {}
            column['func_name'] = ''
            column['rip'] = ''
            column['title'] = ''
            column['bugat'] = ''
            column['ripmod'] = ''
            column['ver'] = ''
            column['comm'] = ''
            column['unload'] = ''
            column['softlockup_modcheck'] = ''
            column['calltrace_list'] = []
            column['calltrace'] = ''
            extract_calltrace(column,request["calltrace"])
            if len(column['calltrace']) > 0:
                calltrace_extrack = "%s$%s"%(column['func_name'],column['calltrace'])
            elif len(column['func_name']) > 0:
                calltrace_extrack = column['func_name']

        try:
            create_knowledge(db, Knowledge(
                issuedesc=request["issuedesc"], logs=request["logs"], calltrace=request["calltrace"],calltrace_extrack=calltrace_extrack,
                funcs=request["funcs"], create_time=datetime.now(), issuelink=request["issuelink"],
                diagret=request["diagret"],field=request["field"]))
            retdict["success"] = True

        except  Exception as e:
            traceback.print_exc()
            logger.exception(e)
            retdict["errmsg"] += "insert into database failed: %s\n"%e
            pass

    except Exception as e:
        traceback.print_exc()
        logger.exception(e)
        pass
    return retdict

@app.post("/api/v1/knowledge/match")
async def knowledge_match(request: dict):
    retdict = {"success":False,"errmsg":"","issuedesc":"","issuelink":"","diagret":"","field":""}
    param_list = ["source"]

    try:
        errmsg = ""
        for param in param_list:
            if param not in request:
                errmsg += "Missing parametre: %s\n"%param
            else:
                if len(request[param]) == 0:
                    errmsg += "Parametre: %s could not be empty!\n"%param

        if "calltrace" not in request and "funcs" not in request and "logs" not in request:
            errmsg += "logs, funcs and calltrace could not be all empty!\n"

        retdict["errmsg"] = errmsg

        if len(errmsg) > 0:
            return retdict

        retdict["success"] = True
        has_ret = 0
        try:
            if "calltrace" in request:
                if len(request["calltrace"]) > 0:
                    calltrace_extrack = request["calltrace"]
                    if len(request["calltrace"]) > 0:
                        column = {}
                        column['func_name'] = ''
                        column['rip'] = ''
                        column['title'] = ''
                        column['bugat'] = ''
                        column['ripmod'] = ''
                        column['ver'] = ''
                        column['comm'] = ''
                        column['unload'] = ''
                        column['softlockup_modcheck'] = ''
                        column['calltrace_list'] = []
                        column['calltrace'] = ''
                        extract_calltrace(column,request["calltrace"])
                        if len(column['calltrace']) > 0:
                            calltrace_extrack = "%s$%s"%(column['func_name'],column['calltrace'])
                        elif len(column['func_name']) > 0:
                            calltrace_extrack = column['func_name']

                    knowledges = get_knowledge_by_calltrace(db,calltrace_extrack)
                    if len(knowledges) > 0:
                        retdict["issuedesc"] = knowledges[0].issuedesc
                        retdict["issuelink"] = knowledges[0].issuelink
                        retdict["diagret"] = knowledges[0].diagret
                        retdict["field"] = knowledges[0].field
                        has_ret = 1

            if "logs" in request:
                if len(request["logs"]) > 0:
                    knowledges = get_knowledge_by_logs(db,request["logs"])
                    if len(knowledges) > 0:
                        retdict["issuedesc"] = knowledges[0].issuedesc
                        retdict["issuelink"] = knowledges[0].issuelink
                        retdict["diagret"] = knowledges[0].diagret
                        retdict["field"] = knowledges[0].field
                        has_ret = 1

            if "funcs" in request:
                if len(request["funcs"]) > 0:
                    knowledges = get_knowledge_by_funcs(db,request["funcs"])
                    if len(knowledges) > 0:
                        retdict["issuedesc"] = knowledges[0].issuedesc
                        retdict["issuelink"] = knowledges[0].issuelink
                        retdict["diagret"] = knowledges[0].diagret
                        retdict["field"] = knowledges[0].field
                        has_ret = 1

            if has_ret == 0:
                retdict["success"] = False

            try:
                create_knowledge_record(db, KnowledgeRecord(
                    recordtime=datetime.now(), logs=request["logs"], calltrace=request["calltrace"],
                    funcs=request["funcs"],source=request["source"], knowledge_ret=json.dumps(retdict,ensure_ascii=False)))

            except Exception as e:
                traceback.print_exc()
                logger.exception(e)
                pass


        except  Exception as e:
            traceback.print_exc()
            logger.exception(e)
            retdict["errmsg"] += "search database failed: %s\n"%e
            retdict["success"] = False
            pass

    except:
        traceback.print_exc()
        pass
    return retdict

def init_framwork():
    SysomFramework\
        .init(YAML_CONFIG) \
        .load_plugin_cls(CmgPlugin) \
        .start()
    logger.info("SysomFramework init finished!")


@app.on_event("startup")
async def on_start():
    init_framwork()
    
    #############################################################################
    # Perform some microservice initialization operations over here
    #############################################################################


@app.on_event("shutdown")
async def on_shutdown():
    pass
